package cn.symbio.basic.aspect;

import cn.symbio.basic.util.HttpContextUtils;
import cn.symbio.basic.util.IPUtils;
import cn.symbio.log.domain.LogSys;
import cn.symbio.log.service.ILogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;


/**
 * 定义切面
 */
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private ILogService logService;

    /**
     * 空方法解析表达式
     */
    @Pointcut("@annotation(cn.symbio.basic.note.SysLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 获取时间戳
        long timeMillis = System.currentTimeMillis();
        // 执行方法返回
        Object result = point.proceed();
        // 获取方法执行时长
        long time = System.currentTimeMillis() - timeMillis;
        // 调用添加方法
        saveSysLog(point,time);
        // 返回前端
        return result;
    }

    /**
     * 保存日志信息
     * @param joinPoint
     * @param time
     */
    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        // 日志实体类
        LogSys log = new LogSys();
        // 获取方法上注解
        cn.symbio.basic.note.SysLog annotation = method.getAnnotation(cn.symbio.basic.note.SysLog.class);
        // 添加注解信息
        if (annotation != null) {
            log.setOperation(annotation.value());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = methodSignature.getName();
        log.setMethod(className + "." + methodName + "()");

        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        try{
            String params = Arrays.toString(args);
            log.setParams(params);
        }catch (Exception e){

        }
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        log.setIp(IPUtils.getIpAddr(request));

        log.setTime(time);
        log.setCreate_date(new Date());
        //保存系统日志
        logService.save(log);
    }
}
